<template>
  <!--   【1】搜索条件   -->
  <Space style="margin: 6px 0 6px 20px">
    查询条件：
    <Select style="width: 180px" v-model:value="state.searchData.projectId" placeholder="课题组" :options="state.researchGroupList" :field-names="{ label: 'name', value: 'id' }" allowClear />
    <Input v-model:value="state.searchData.originalSerial" allowClear placeholder="样本编号" />
    <Input v-model:value="state.searchData.name" allowClear placeholder="样本名称" />
    <Input v-model:value="state.searchData.f" allowClear placeholder="样本类型" />
    <Input v-model:value="state.searchData.serialLike" allowClear placeholder="数字编号" />
    <Button type="blue-white" @click="searchFn">查询</Button>
  </Space>
  <!--   【2】搜索表格   -->
  <vxe-table
    :row-config="{ height: 40, isHover: true }"
    :data="state.tableList"
    :loading="state.tableLoading"
    :expand-config="{ accordion: true }"
    ref="tableRef"
    max-height="300px"
    @toggle-row-expand="toggleRowExpandFn"
  >
    <vxe-column type="expand" width="80">
      <template #content="{ row }">
        <!--   【3】子表格-s   -->
        <vxe-table :data="row.subSpecimens ?? []" ref="subTableRef" align="center" @checkbox-change="checkboxChangeFn" @checkbox-all="checkboxChangeFn">
          <vxe-column type="checkbox" title="" width="60" />
          <vxe-column
            field="sortIndex"
            title="位置"
            :formatter="
              ({ cellValue }) => {
                if (cellValue > row?.boxCols) {
                  return `${Math.ceil(cellValue / row?.boxCols)}-${(cellValue % row?.boxCols) + 1}`;
                } else {
                  return '1-' + (cellValue + 1);
                }
              }
            "
          />
          <vxe-column field="originalSerial" title="样本编号" />
          <vxe-column field="name" title="样本名称" />
          <vxe-column
            title="样本类型"
            :formatter="
              ({ row }) => {
                return row.extDataList?.find((item) => item?.key === 'specimen_type')?.value;
              }
            "
          />
          <vxe-column field="sampleTime" title="采样日期" />
          <vxe-column field="serial" title="数字编号" />
          <vxe-column title="容量" :formatter="({ row }) => `${unitCheck(row.capacity, row.countUnit)}`" />
        </vxe-table>
        <!--   【3】子表格-e   -->
      </template>
    </vxe-column>
    <vxe-column field="serial" title="冻存盒编号" />
    <vxe-column field="boxType" title="冻存盒类型" />
    <vxe-column field="storageDesp" title="存储位置" />
  </vxe-table>
</template>

<script setup lang="ts">
import { Input, Select, Space } from 'ant-design-vue';
import { DownOutlined } from '@ant-design/icons-vue';
import Button from '@/framework/components/basic/button/button.vue';
import { taskSearch } from '@/api/base/task-data';
import { getOutputData } from '@/modules/sample_manage/api/out_input';
import { nextTick, reactive, ref, watch } from 'vue';
import { VxeTableInstance } from 'vxe-table';
import { unitCheck } from '@/libs/utils';
const props = defineProps<{
  range?;
}>();
const emits = defineEmits<{
  (e: 'checkedChange', map: any): void;
}>();
const state = reactive({
  tableLoading: false,
  searchData: {},
  researchGroupList: [],

  tableList: [],
  checkedMap: new Map(),
  curData: {},
});
const subTableRef = ref<VxeTableInstance>();

watch(
  () => props.range,
  () => {
    state.searchData.storageIds = props.range;
    searchFn();
  },
);
/*
 * table
 * */
// 切换展开状态
const toggleRowExpandFn = ({ expanded, row }) => {
  if (!expanded) return;
  state.curData = row;
  nextTick(() => {
    if (!state.checkedMap.has(row)) return;
    subTableRef.value?.setCheckboxRow(state.checkedMap.get(row), true);
  });
};
// 切换选中状态
const changeCheckedStateFn = (map, key?) => {
  state.checkedMap = map;
  subTableRef.value?.setAllCheckboxRow(false);
  if (key === state.curData) {
    if (map.get(key)?.length) {
      subTableRef.value?.setCheckboxRow(state.checkedMap.get(key), true);
    }
  }
};

/*
 * sub-table
 *  */
// 选中函数
const checkboxChangeFn = ({ records }) => {
  if (state.curData?.subSpecimens?.length && records.length < state.curData.subSpecimens.length) {
    state.curData.isNotAll = true;
  } else {
    state.curData.isNotAll = false;
  }
  if (records?.length) {
    state.checkedMap.set(state.curData, records);
  } else {
    state.checkedMap.delete(state.curData);
  }
  emits('checkedChange', state.checkedMap);
};

/*
 * fetchData
 * */
// 搜索数据（课题组数据）
const getResearchGroupList = async () => {
  let params = {
    pageNum: 1, // 当前页数
    pageSize: 1000, // 页面大小
    'orderBy[0].field': 'createTime', // 默认排序字段
    'orderBy[0].order': 'desc', // 默认排序方式
  };
  let res = await taskSearch(params);
  state.researchGroupList = res.result.data;
};
// 表格数据（样本盒数据）
const searchFn = async (data?) => {
  state.tableLoading = true;
  state.searchData.extDataList = [
    {
      name: 'specimen_type',
      value: state.searchData.f,
    },
  ];
  let params = { type: 4, queryExtData: true, pageNum: 1, pageSize: 100000, 'orderBy[0].field': 'id', 'orderBy[0].order': 'asc', ...data };
  const res = await getOutputData(state.searchData, params);
  state.tableList = res.result.data.filter((item) => {
    return item.subSpecimens && item.subSpecimens?.length > 0;
  });
  state.tableLoading = false;
};

const init = () => {
  getResearchGroupList();
  searchFn();
};
init();

defineExpose({
  changeCheckedStateFn,
});
</script>

<style scoped lang="less">
:deep(.vxe-icon--arrow-right:before) {
  border-top-color: #606266;
  border-right-color: #606266;
}
</style>
